<template>
	<view class="order-container">

		<!-- 顶部标签页 -->
		<u-tabs :list="tabList" :current="currentTab" @change="changeTab" :is-scroll="false" active-color="#2979ff"></u-tabs>

		<!-- 单据类型按钮 -->
		<view class="doc-type-buttons">
			<u-button :type="docType === 'sales' ? 'primary' : 'default'" size="mini" @click="changeDocType('sales')">出货</u-button>
			<u-button :type="docType === 'return' ? 'primary' : 'default'" size="mini" @click="changeDocType('return')">退货</u-button>
			<u-button :type="docType === 'payment' ? 'primary' : 'default'" size="mini" @click="changeDocType('payment')">收款</u-button>
		</view>

		<!-- 时间和客户选择 -->
		<view class="info-section">
			<u-cell-group :border="false">
				<u-cell title="时间" :value="selectedDate" isLink @click="selectDate">
					<u-icon slot="icon" name="clock" size="20" customStyle="margin-right: 10rpx;"></u-icon>
				</u-cell>
				<u-cell title="客户" :value="selectedCustomer" isLink @click="selectCustomer">
					<u-icon slot="icon" name="account" size="20" customStyle="margin-right: 10rpx;"></u-icon>
				</u-cell>
			</u-cell-group>
		</view>

		<!-- 货品选择区 -->
		<view class="goods-section">
			<view class="goods-header">
				<text class="title">选中货品 ({{ selectedGoodsCount }})</text>
				<text class="total-amount">合计金额: ¥{{ totalAmount.toFixed(2) }}</text>
			</view>
			<view class="add-goods-button" @click="addGoods">
				<u-icon name="plus" size="30" color="#2979ff"></u-icon>
			</view>

			<!-- 货品列表或空状态 -->
			<view class="goods-list-container">
				<u-empty v-if="selectedGoodsCount === 0" mode="car" :text="emptyText"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabList: [
                    { name: '销售' },
                    { name: '进货' },
                    { name: '其他收入' },
                    { name: '其他支出' }
                ],
				currentTab: 0, // 默认选中'销售'
				docType: 'sales', // 默认单据类型为'出货'
				showDatePicker: false,
				currentDate: Number(new Date()), // u-datetime-picker 需要时间戳
				selectedDate: new Date().toISOString().split('T')[0],
				selectedCustomer: '零售客户', // 默认客户
                selectedGoodsCount: 0,
                totalAmount: 0,
                emptyText: '购物车里空空如也\n扫描或点击"+"选择商品吧'
			};
		},
		methods: {
			changeTab(e) {
				// 识别参数类型并提取索引
				let index;
				if (typeof e === 'object') {
					// 如果是对象参数（可能是u-tabs传入的完整项）
					if (e.index !== undefined) {
						index = e.index; // 使用对象的index属性
					} else if (e.name !== undefined) {
						// 如果没有index但有name，尝试在tabList中查找匹配的项
						index = this.tabList.findIndex(item => item.name === e.name);
					} else {
						console.log('无法识别的参数格式:', e);
						return;
					}
				} else {
					// 如果是数字索引
					index = e;
				}
				
				// 忽略相同标签的点击
				if (this.currentTab === index) return;
				
				// 添加安全检查，确保index有效且对应的tab项存在
				if (index < 0 || index >= this.tabList.length || !this.tabList[index]) {
					console.log('无效的标签索引:', index);
					return;
				}
				
				this.currentTab = index;
				const tabName = this.tabList[index].name;
				
				if (tabName === '销售') {
					this.docType = 'sales';
				} else if (tabName === '进货') {
					// 添加加载提示并跳转到进货页面
					uni.showLoading({
						title: '正在跳转...',
						mask: true
					});
					
					// 添加延迟以显示加载状态
					setTimeout(() => {
						uni.redirectTo({ 
							url: '/pages/purchase/purchase',
							success: () => {
								uni.hideLoading();
								console.log('成功跳转到进货页面');
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({
									title: '跳转失败',
									icon: 'none',
									duration: 2000
								});
								console.error('跳转失败:', err);
							}
						});
					}, 300);
				} else if (tabName === '其他收入') {
					// 添加加载提示并跳转到其他收入页面
					uni.showLoading({
						title: '正在跳转...',
						mask: true
					});
					
					// 添加延迟以显示加载状态
					setTimeout(() => {
						uni.redirectTo({ 
							url: '/pages/income/index',
							success: () => {
								uni.hideLoading();
								console.log('成功跳转到其他收入页面');
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({
									title: '跳转失败',
									icon: 'none',
									duration: 2000
								});
								console.error('跳转失败:', err);
							}
						});
					}, 300);
				} else if (tabName === '其他支出') {
					// 添加加载提示并跳转到其他支出页面
					uni.showLoading({
						title: '正在跳转...',
						mask: true
					});
					
					// 添加延迟以显示加载状态
					setTimeout(() => {
						uni.redirectTo({ 
							url: '/subPack/expense/index',
							success: () => {
								uni.hideLoading();
								console.log('成功跳转到其他支出页面');
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({
									title: '跳转失败',
									icon: 'none',
									duration: 2000
								});
								console.error('跳转失败:', err);
							}
						});
					}, 300);
				}
			},
			changeDocType(type) {
                this.docType = type;
				// 提供视觉反馈
				uni.showToast({ 
					title: `已切换到${type === 'sales' ? '出货' : type === 'return' ? '退货' : '收款'}`,
					icon: 'none',
					duration: 1000
				});
			},
			selectDate() {
				uni.showLoading({
					title: '加载日期选择器...',
					mask: true
				});
				
				setTimeout(() => {
					uni.hideLoading();
					// 打开日期选择器
					const picker = document.createElement('input');
					picker.type = 'date';
					picker.value = this.selectedDate;
					picker.style.position = 'fixed';
					picker.style.top = '0';
					picker.style.left = '0';
					picker.style.opacity = '0';
					document.body.appendChild(picker);
					
					picker.onchange = (e) => {
						this.selectedDate = e.target.value;
						document.body.removeChild(picker);
						uni.showToast({
							title: `已选择日期: ${this.selectedDate}`,
							icon: 'none',
							duration: 1500
						});
					};
					
					picker.click();
					
					// 如果用户没有选择，则移除元素
					setTimeout(() => {
						if (document.body.contains(picker)) {
							document.body.removeChild(picker);
						}
					}, 5000);
				}, 300);
			},
			selectCustomer() {
				// 跳转到客户选择页面或弹出选择框
				uni.showLoading({
					title: '加载客户列表...',
					mask: true
				});
				
				// 模拟跳转到客户选择页面
				setTimeout(() => {
					// 这里可以替换为实际的客户选择页面跳转
					uni.hideLoading();
					
					// 弹出选择客户的模态框
					uni.showActionSheet({
						itemList: ['零售客户', '批发客户', '企业客户', '新增客户'],
						success: (res) => {
							const customers = ['零售客户', '批发客户', '企业客户', '新增客户'];
							if (res.tapIndex === 3) {
								// 新增客户选项
								uni.showToast({
									title: '前往新增客户',
									icon: 'none',
									duration: 1500
								});
								// 这里可以添加跳转到新增客户页面的逻辑
							} else {
								this.selectedCustomer = customers[res.tapIndex];
								uni.showToast({
									title: `已选择: ${this.selectedCustomer}`,
									icon: 'none',
									duration: 1500
								});
							}
						},
						fail: () => {
							console.log('客户选择取消');
						}
					});
				}, 300);
			},
			addGoods() {
				// 跳转到货品选择页面或弹出选择框
				uni.showLoading({
					title: '正在加载...',
					mask: true
				});
				
				uni.navigateTo({
					url: '/pages/goods/add',
					success: () => {
						uni.hideLoading();
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '跳转失败，请重试',
							icon: 'none',
							duration: 2000
						});
						console.error('跳转失败:', err);
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
.order-container {
	background-color: #f5f7fa;
	min-height: 100vh;
    font-size: 28rpx;
}

// 顶部标题样式
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20rpx;
    height: 80rpx;
    background-color: #fff;
    
    .page-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #000;
        text-align: center;
        flex: 1;
    }
    
    .header-icons {
        display: flex;
        align-items: center;
    }
}

// -- 顶部 Tabs 优化 --
/deep/ .u-tabs {
    background-color: #fff !important;
}
/deep/ .u-tabs__wrapper__nav__line {
    display: none !important;
}
/deep/ .u-tabs__wrapper__nav__item {
    padding: 0 40rpx !important;
    height: 80rpx !important;
    line-height: 80rpx !important;
    font-size: 28rpx !important;
}
/deep/ .u-tabs__wrapper__nav__item.is-active {
    font-weight: bold;
    color: #2979ff !important;
    position: relative;
    background-color: rgba(41, 121, 255, 0.08);
}
/deep/ .u-tabs__wrapper__nav__item.is-active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background-color: #2979ff;
}

// -- 单据类型按钮优化 --
.doc-type-buttons {
	display: flex;
	padding: 15rpx 25rpx;
	background-color: #fff;
    border-bottom: 1rpx solid #e8e8e8;
    gap: 20rpx;

	.u-button {
        flex: 1;
		margin-right: 0;
        border-radius: 8rpx !important;
        height: 60rpx !important;
        line-height: 60rpx !important;
        font-size: 26rpx !important;
        border-width: 1rpx !important;
        border-style: solid !important;

        &,
        &.u-button--default {
            background-color: #fff !important;
            border-color: #d9d9d9 !important;
            color: #595959 !important;
        }
        &.u-button--primary {
            background-color: #e6f7ff !important;
            border-color: #91d5ff !important;
            color: #1890ff !important;
        }
        &::after {
            border: none !important;
        }
	}
}

// -- 信息区优化 --
.info-section {
	background-color: #fff;
	margin-top: 16rpx;
    border-top: 1rpx solid #e8e8e8;
    border-bottom: 1rpx solid #e8e8e8;

    /deep/ .u-cell {
        padding: 22rpx 30rpx !important;
        align-items: center;
    }
    /deep/ .u-cell__body {
        font-size: 28rpx !important;
        color: #333 !important;
    }
    /deep/ .u-cell__left-icon-wrap {
        margin-right: 12rpx !important;
    }
    /deep/ .u-icon__icon {
        color: #8c8c8c !important;
        font-size: 36rpx !important;
    }
    /deep/ .u-cell__value {
        font-size: 28rpx !important;
        color: #595959 !important;
        text-align: right;
    }
    /deep/ .u-cell__right-icon-wrap {
        margin-left: 8rpx !important;
        color: #bfbfbf !important;
    }
    /deep/ .u-line {
        border-bottom: 1rpx solid #f0f0f0 !important;
    }
    /deep/ .u-cell-group > uni-view:last-child .u-line {
        display: none !important;
    }
}

// -- 货品选择区优化 --
.goods-section {
	background-color: #fff;
	margin-top: 16rpx;
    border-top: 1rpx solid #e8e8e8;
    border-bottom: 1rpx solid #e8e8e8;

	.goods-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.title {
			font-size: 28rpx;
			color: #333;
		}
		.total-amount {
			font-size: 28rpx;
			color: #333;
            font-weight: 500;
		}
	}

	.add-goods-button {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx 0;
		border-bottom: 1rpx dashed #dcdfe6;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        
        &:active {
            background-color: rgba(0, 0, 0, 0.05);
        }
        
        .u-icon {
            font-size: 50rpx !important;
            font-weight: bold;
        }
	}

    .goods-list-container {
        padding: 60rpx 0 80rpx;
        min-height: 350rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f7f8fa;

        /deep/ .u-empty__icon {
            width: 180rpx !important;
            height: 180rpx !important;
        }
        /deep/ .u-empty__text {
            font-size: 26rpx !important;
            color: #bfbfbf !important;
            margin-top: 20rpx !important;
            text-align: center;
            line-height: 1.6;
        }
    }
}
</style>
